﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace G.SL.Net.APISuite
{
    /// <summary>
    /// 无签名请求
    /// </summary>
    public class SampleClient : IClient
    {
        public void Execute<T>(Request<T> request, Action<T> callback) where T : IResponse
        {
            HttpRequest req = null;
            if (request.RequestMethod == HttpMethod.Get)
            {
                HttpGet get = new HttpGet(request.Path);
                foreach (var item in request.GetParameters())
                {
                    if (!string.IsNullOrEmpty(item.Value))
                        get.Params.Add(item.Key, item.Value);
                }
                req = get;
            }
            else if (request.RequestMethod == HttpMethod.Post)
            {
                HttpPost post = new HttpPost(request.Path);
                post.PostData = BuildQuery(request.GetParameters());
                req = post;
            }

            req.Request((status, str) =>
            {
                T obj;
                try
                {
                    if (status == null)
                    {
                        obj = Utils.SerializerHelp.JsonDeserialize<T>(str);
                    }
                    else
                    {
                        obj = Activator.CreateInstance<T>();
                        obj.Exception = status;
                    }
                    obj.Body = str;
                }
                catch (Exception ex)
                {
                    obj = Activator.CreateInstance<T>();
                    obj.Exception = ex;
                }
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    callback(obj);
                });
            });
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        public byte[] BuildQuery(IDictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;
            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }
                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(Uri.EscapeDataString(value));
                    hasParam = true;
                }
            }
            return System.Text.Encoding.UTF8.GetBytes(postData.ToString());
        }

    }
}
